import { useCallback, useEffect, useMemo, useState } from "react";
import { ConfigProvider, Table } from "antd";
import { GlobalRegistry } from "@inbiz/core";
import { getMessage } from '@inbiz/react';
import EmptySetting from '@inbiz/basic/EmptySetting';
import {commonLang} from '@inbiz/utils'
import { DynamicListTableProps } from '../../interfaces';
import Pagination from "./Pagination";
import styles from '../index.less';

const DynamicListTable = (props: DynamicListTableProps) => {
  const { menu, selectType, columns, dataSource, total, current, pageSize, loadding, storageField, scroll, selectValue, options, showField, memuRef, selectRef, $options, $current, $pageSize, $searchIpt, search } = props;

  const [locale, $locale] = useState(commonLang[GlobalRegistry.getDesignerLanguage()?.toLocaleLowerCase() as keyof typeof commonLang])
  useEffect(() => {
    $locale(commonLang[GlobalRegistry.getDesignerLanguage()?.toLocaleLowerCase() as keyof typeof commonLang])
  }, [GlobalRegistry.getDesignerLanguage()]);

  const onRow = useCallback((record: any) => {
    if (selectType) {
      return {
        onClick: (e) => {
          e.stopPropagation();
          rowClick(record);
        },
      };
    }
    return {
      onClick: (e) => {
        e.stopPropagation();
        let opt: { value: string; label: string }[] = options;
        let check = opt.every((item) => item.value !== record[storageField]);
        if (record[storageField]) {
          if (check) {
            opt.push({
              value: record[storageField],
              label: record[showField],
            });
            $options(opt);
          }
          props.onChange && props.onChange(record[storageField]);
        }
        hideSelect();
        $current(1);
        $searchIpt('');
        selectRef.current?.blur();
      },
    };
  }, [selectType, options, storageField, showField]);

  // 收起下拉弹窗浮层
  const hideSelect = () => {
    let timer = setTimeout(() => {
      if (memuRef?.current) {
        let memuDom = memuRef.current?.getElementsByClassName('rc-virtual-list-holder-inner');
        if (memuDom.length) {
          let optionDom = memuDom[0] as HTMLDivElement;
          if (optionDom.childNodes.length) {
            let item = optionDom.childNodes[0] as HTMLDivElement;
            item.click();
          }
        }
      }
      clearTimeout(timer);
    }, 0);
  };

  // 多选选择变化
  const onChange = useCallback(
    (selectedRowKeys, record) => {
      let selectedRowKeysFilter = selectedRowKeys.filter((item: any) => item);
      let values: string[] = Array.isArray(selectValue)
        ? selectValue
        : selectValue
          ? [selectValue]
          : [];
      let arr = [...values];
      // 扩展代码onSelect ******** begin
      let oldArr: any[] = [];
      dataSource.map((item: { [key: string]: any }) => {
        if (arr.indexOf(item[storageField]) >= 0) {
          oldArr.push(item[storageField]);
        }
      });
      if (oldArr.length < selectedRowKeys.length) {
        // 选中
        let addArr: any[] = [];
        let addArrOpt: any[] = [];
        selectedRowKeys.map((item: any) => {
          if (oldArr.indexOf(item) < 0) {
            addArr.push(item);
            let fil = record.filter((val: any) => val[storageField] === item);
            addArrOpt.push(...fil);
          }
        });
        // props.emit?.('onSelect', addArr, true, addArrOpt);
      } else {
        // 取消选中
        let delArr: any[] = [];
        let delArrOpt: any[] = [];
        oldArr.map((item: any) => {
          if (selectedRowKeys.indexOf(item) < 0) {
            delArr.push(item);
            let fil = dataSource.filter((val: any) => val[storageField] === item);
            delArrOpt.push(...fil);
          }
        });
        // props.emit?.('onSelect', delArr, false, delArrOpt);
      }
      // 扩展代码onSelect ******** end
      // 步骤1：将选中key数组清除当前页的所有key
      dataSource.map((item: { [key: string]: any }) => {
        if (arr.indexOf(item[storageField]) >= 0) {
          arr.splice(arr.indexOf(item[storageField]), 1);
        }
      });
      // 步骤2：key数组加上当前页选中的所有key
      arr.push(...selectedRowKeysFilter);
      props.onChange && props.onChange(arr);
      // 步骤3：将当前页选中的数据加value、label键值对入option实现回显
      let opts = [...options];
      record.map((item: any) => {
        if (!opts.some((val) => val.value === item[storageField]) && item[storageField]) {
          opts.push({
            value: item[storageField],
            label: item[showField],
          });
        }
      });
      $options(opts);
    },
    [selectValue, dataSource, storageField, showField, options],
  );

  const rowSelection = useMemo(() => {
    if (selectType) {
      return {
        selectedRowKeys: Array.isArray(selectValue)
          ? selectValue
          : selectValue
            ? [selectValue]
            : [],
        onChange: onChange,
      }
    }
    return undefined
  }, [selectType, selectValue, onChange])

  // 多选点击行选择/取消
  const rowClick = useCallback(
    (record: any) => {
      if (Array.isArray(selectValue)) {
        let select = [...selectValue];
        let opts = [...options];
        if (select?.indexOf(record[storageField]) > -1) {
          let idx = select?.indexOf(record[storageField]);
          if (idx || idx === 0) select?.splice(idx, 1);
        } else {
          select.push(record[storageField]);
          let haveOpt = opts.every((item) => item.value !== record[storageField]);
          haveOpt &&
            opts.push({
              value: record[storageField],
              label: record[showField],
            });
        }
        props.onChange && props.onChange(select);
        $options(opts);
      }
    },
    [selectValue, options, showField],
  );

  const rowClassName = useCallback((record: any) => {
    if (
      (record[storageField] === selectValue && selectValue) ||
      (Array.isArray(selectValue) &&
        selectValue.some((item) => item === record[storageField]))
    ) {
      return styles['item-active'];
    }
    return '';
  }, [selectValue, storageField])

  return (
    <div
      onKeyDown={(e) => {
        e.stopPropagation();
      }}
    >
      <div className="dynamic-list-select-memu" ref={memuRef}>
        {menu}
      </div>
      <ConfigProvider locale={locale}>
        {columns && Array.isArray(columns) && columns.length ? (
          <>
            <Table
              columns={columns}
              dataSource={dataSource}
              loading={loadding}
              size="small"
              rowKey={storageField}
              scroll={scroll}
              showHeader={props.showconfig?.showHeader ?? true}
              pagination={false}
              rowSelection={rowSelection}
              rowClassName={selectType ? undefined : rowClassName}
              className={`${styles['dynamic-list-select-table']}`}
              onRow={onRow}
            />
            <Pagination
              options={[5, 10, 20, 30, 40, 50]}
              total={total}
              current={current}
              pageSize={pageSize}
              refs={selectRef}
              onChange={(e: any) => {
                $current(e.current);
                $pageSize(e.pageSize);
                search(e.current, e.pageSize);
              }}
            />
          </>
        ) : (
          <div className="select-table-nocolumns-box">
            <EmptySetting
              icon="icon-dongtailiebiao-weipeizhiqueshengtu"
              description={getMessage('EformDynamicList.noDisplayConfiguration')}
            />
          </div>
        )}
      </ConfigProvider>
    </div>
  )
}

export default DynamicListTable;